package cn.qyd.aqs;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 邱运铎
 * @date 2024-03-19 14:03
 */
public class ReentrantLockCompareSynchronizedDemo {
    private static final int NUM_THREADS = 10;
    private static final int NUM_INCREMENT = 1_000_000;

    private int count1 = 0;
    private int count2 = 0;

    private final ReentrantLock lock = new ReentrantLock();
    private final Object sync = new Object();

    public void incrementCount1() {
        synchronized (sync) {
            count1++;
        }
    }

    public void incrementCount2() {
        lock.lock();
        try {
            count2++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockCompareSynchronizedDemo demo = new ReentrantLockCompareSynchronizedDemo();
        Thread[] threads = new Thread[NUM_THREADS];

        //test Synchronized
        long startTime = System.nanoTime();
        for (int i = 0; i < NUM_THREADS; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < NUM_INCREMENT; j++) {
                    demo.incrementCount1();
                }
            });
            threads[i].start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        long endTime = System.nanoTime();
        System.out.println("Synchronized time: " + (endTime - startTime) + "ns");

        //test ReentrantLock
        startTime = System.nanoTime();
        for (int i = 0; i < NUM_THREADS; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < NUM_INCREMENT; j++) {
                    demo.incrementCount2();
                }
            });
            threads[i].start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        endTime = System.nanoTime();
        System.out.println("ReentrantLock time: " + (endTime - startTime) + "ns");
    }

}
